// subPages/pensionService/newKitchen/newKitchen.js
const app = getApp();
var util = require('../../../utils/util');
var num=20,p=1,loadMoreView,type='kitchen'
Page({

  /**
   * 页面的初始数据
   */
  data: {
      themeColor:app.globalData.themeColor,
      totalMoney:0,
      changeList:[
          {
              type:1,
              text:'普通特膳',
              img:'/resources/pensionService/putong.png'
          },
          {
              type:2,
              text:'疾病配餐',
              img:'/resources/pensionService/teshu.png'
          }

      ],
      tabList:[
          {
              id:0,
              name:'本周菜谱'
          },{
                id:1,
              name:'下周菜谱'
          }
      ],
      currentNav:0,
      navList:[],
      navItemCurr:0,
      isFixed:false
  },
    getHeadH(){
        let _this = this;
        const query = wx.createSelectorQuery()
        query.select('.fixed-box').boundingClientRect(
            function (res) {
                _this.setData({
                    topH:res.height+20
                })
            }
        ).exec();
    },
  changeNav(e){
    let _this = this;
    let id = e.currentTarget.dataset.id;
    _this.setData({
        currentNav:id,
        productList:[]
    })
    _this. getKitchenContent(id,_this.data.kitchenId,_this.data.type);
  },
    changeType(e){
      let type = e.currentTarget.dataset.type,
          _this = this;
      _this.setData({
          type:type
      })
      _this.setNavBarTitle(type);
      _this.getKitchenClass(type);
      _this.getHeadH();
    },
    //弹框
    clickModal(){
        if(this.data.showModalStatus){
            this.hideModal();
        }else{
            this.showModal();
        }
    },
    //获取当前日期周一
    getWeek(){
        var _this = this;
        var nowTemp = new Date();//当前时间
        var oneDayLong = 24*60*60*1000 ;//一天的毫秒数
        var c_time = nowTemp.getTime() ;//当前时间的毫秒时间
        var c_day = nowTemp.getDay()||7;//当前时间的星期几
        var t_time = c_time + oneDayLong;
        var tomorrow = new Date(t_time);
        var t_year = tomorrow.getFullYear();
        var t_month = (tomorrow.getMonth()+1)>9?(tomorrow.getMonth()+1):'0'+(tomorrow.getMonth()+1);
        var t_date = tomorrow.getDate()>9?tomorrow.getDate():'0'+tomorrow.getDate();
        var m_time = c_time - (c_day-1)*oneDayLong;//当前周一的毫秒时间
        var s_time = c_time + (7-c_day)*oneDayLong;//当前周日的毫秒时间
        var m_next_time = c_time + (8 - c_day)*oneDayLong;//下周周一的毫秒时间
        var s_next_time = c_time + (14 - c_day)*oneDayLong;//下周周日的毫秒时间
        var sunday = new Date(s_time);//设置周日时间对象
        var monday = new Date(m_time);//设置周一时间对象
        var monday_next = new Date(m_next_time);
        var sunday_next = new Date(s_next_time);
        var m_year = monday.getFullYear();
        var s_year = sunday.getFullYear();
        var m_next_year = monday_next.getFullYear();
        var s_next_year = sunday_next.getFullYear();
        var m_month = (monday.getMonth()+1)>10?(monday.getMonth()+1):'0'+(monday.getMonth()+1);
        var s_month = (sunday.getMonth()+1)>10?(sunday.getMonth()+1):'0'+(sunday.getMonth()+1);
        var m_next_month = (monday_next.getMonth()+1)>10?(monday_next.getMonth()+1):'0'+(monday_next.getMonth()+1);
        var s_next_month = (sunday_next.getMonth()+1)>10?(sunday_next.getMonth()+1):'0'+(sunday_next.getMonth()+1);
        var m_date = monday.getDate()>10?monday.getDate():'0'+monday.getDate();
        var s_date = sunday.getDate()>10?sunday.getDate():'0'+sunday.getDate();
        var m_next_date = monday_next.getDate()>10?monday_next.getDate():'0'+monday_next.getDate();
        var s_next_date = sunday_next.getDate()>10?sunday_next.getDate():'0'+sunday_next.getDate();
        _this.setData({
            dateInfo:{
                monday:`${m_year}-${m_month}-${m_date}`,
                tomorrow:`${t_year}-${t_month}-${t_date}`,
                sunday:`${s_year}-${s_month}-${s_date}`,
                mondayNext:`${m_next_year}-${m_next_month}-${m_next_date}`,
                sundayNext:`${s_next_year}-${s_next_month}-${s_next_date}`,
            }
        })
    },
    showModal: function () {
        // 显示遮罩层
        var animation = wx.createAnimation({
            duration: 200,
            timingFunction: "linear",
            delay: 0
        })
        this.animation = animation
        animation.translateY(300).step()
        this.setData({
            animationData: animation.export(),
            showModalStatus: true
        })
        setTimeout(function () {
            animation.translateY(0).step()
            this.setData({
                animationData: animation.export()
            })
        }.bind(this), 200)
    },
    hideModal: function () {
        // 隐藏遮罩层
        var animation = wx.createAnimation({
            duration: 200,
            timingFunction: "linear",
            delay: 0
        })
        this.animation = animation
        animation.translateY(300).step()
        this.setData({
            animationData: animation.export(),
        })
        setTimeout(function () {
            animation.translateY(0).step()
            this.setData({
                animationData: animation.export(),
                showModalStatus: false
            })
        }.bind(this), 200)
    },
    toDetails(e){
      let id = e.currentTarget.dataset.id;
      let type = e.currentTarget.dataset.type;
      wx.navigateTo({
          url:'/subPages/pensionService/kitchenDetails/kitchenDetails?type='+type+'&id='+id
      })
    },
    setNavBarTitle(id){
        if(id == 1){
            util.setNavBarTitle('特膳厨房');
        }else if(id == 2){
            util.setNavBarTitle('疾病配餐');
        }
    },
    //加入购物车
    addShoppingcart(e){
        var _this = this
        if(app.globalData.userId){
            price,num =1,
            productList = _this.data.productList,
            id = e.currentTarget.dataset.id,
            shoppingcartList = _this.data.shoppingcartList;
            for(var i in productList){
                if(id == productList[i].id){
                    price = productList[i].price
                }
            }
            for(var j in shoppingcartList){
                if(id == shoppingcartList[j].product_id){
                    num = ++shoppingcartList[j].num
                }
            }
            _this.getShoppingcartList()
            util.getAjax(`${app.globalData.apiUrl}/operation_community_service_kitchen_product_buycar`,res=>{
                // console.log(res);
                if(res.data.status == 1){
                    util.showToast('购物车添加成功！','none',2000);
                }
                _this.getShoppingcartList()
            },{
                type:1,
                kitchen_id:_this.data.kitchenId,
                product_id:id,
                user_id:app.globalData.userId,
                num:num,
                price:price,
                id:''
            })
        }else{
            util.showModelAll('提示','该功能需要授权登录后使用，请进行授权登录',function(){
                if (app.globalData.userInfo) {
                    //已授权
                    wx.redirectTo({
                        url: '/pages/login/login'
                    })
                }else{
                    // 在没有 open-type=getUserInfo 版本的兼容处理
                    if(app.globalData.isAuthorized){
                        app.userInfoReadyCallback = res => {
                          if (res) {
                            //已授权
                            wx.redirectTo({
                              url: '/pages/login/login'
                            })
                          }else{
                            //未授权
                            wx.navigateTo({
                              url: '/pages/authorizedLogin/authorizedLogin?isLogin='+ false,
                            })
                          }
                        }
                    }else{
                        wx.navigateTo({
                          url: '/pages/authorizedLogin/authorizedLogin?isLogin='+ false,
                        })
                    }
                }
            })
        }
    },
    //切换选项卡
    changeTab(e){
        let _this = this;
        let id = e.currentTarget.dataset.id;
        _this.setData({
            navItemCurr:id,
            productList:[]
        })
        _this.getKitchenContent(_this.data.currentNav,_this.data.kitchenId,_this.data.type)
    },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
       type:options.id
    })
    this.setNavBarTitle(options.id);
    util.setNavBarColor('#ffffff',this.data.themeColor);
  },
  //获取厨房主体
    getKitchen(){
      let _this = this;
      util.getAjax(`${app.globalData.apiUrl}/get_community_service_kitchen`,res=>{
          console.log(res);
          _this.getWeek();
          _this.setData({
              kitchenId:res.data.id
          })
          _this.getKitchenClass(_this.data.type),
          _this.getShoppingcartList();
      },{
          community_id:app.globalData.communityId
      })
    },
    //获取厨房类别分类 1 普通   2特殊膳食
    getKitchenClass(type){
      let _this = this;
      util.getAjax(`${app.globalData.apiUrl}/get_community_service_kitchen_class`,res=>{
          _this.setData({
              navList:res.data,
              currentNav:res.data[0].id
          })
          _this.getHeadH();
          _this.getChangeH();
          _this.getKitchenContent(res.data[0].id,_this.data.kitchenId,_this.data.type)
      },{
          kitchen_id: _this.data.kitchenId,
          type:type
      })
    },
    //获取厨房菜单
    getKitchenContent(classId,kitchenId,type){
      let _this = this;
        // console.log(type);
        if(type==1){
          util.getAjax(`${app.globalData.apiUrl}/get_community_service_kitchen_product`,res=>{
              // console.log(res);
              if(res.data.list.length != 0){
                  var list = [];
                  if(p == 1){
                      list = res.data.list
                  }else{
                      list = _this.data.productList.concat(res.data.list)
                  }
                  _this.setData({
                      productList:list
                  })
              }else{
                _this.setData({
                    productList:[]
                })
              }
              loadMoreView = this.selectComponent("#loadMoreView")
              loadMoreView.loadMoreComplete(res.data,type)
          },{
              type:type,
              class_id:classId,
              kitchen_id:kitchenId,
              num:num,
              p:p
          })
      }else if(type==2){
            if(_this.data.navItemCurr==0){
                // console.log('nav1');
                _this.getTSkitchen(type,classId,kitchenId,_this.data.dateInfo.tomorrow,_this.data.dateInfo.sunday)
          }else if(_this.data.navItemCurr==1){
                // console.log('nav2');
                _this.getTSkitchen(type,classId,kitchenId,_this.data.dateInfo.mondayNext,_this.data.dateInfo.sundayNext)
          }

      }

    },
    //获取特膳厨房菜单
    getTSkitchen(type,classId,kitchenId,sTime,eTime){
        let _this = this;
        util.getAjax(`${app.globalData.apiUrl}/get_community_service_kitchen_product`,res=>{
            console.log(res);
            if(res.data.list.length != 0){
                var list = [];
                if(p == 1){
                    list = res.data.list
                }else{
                    list = _this.data.productList.concat(res.data.list)
                }
                // console.log(list);
                for(var i in list){
                    list[i].week = _this.getWeekday(list[i].date)
                }
                //status 1 午餐   2晚餐
                list = _this.resetList(list);
                console.log(list);

                _this.setData({
                    productList:list
                })
            }else{
                _this.setData({
                    productList:[]
                })
            }
            loadMoreView = this.selectComponent("#loadMoreView")
            loadMoreView.loadMoreComplete(res.data,type)
        },{
            type:type,
            class_id:classId,
            kitchen_id:kitchenId,
            num:num,
            p:p,
            start_time:sTime,
            end_time:eTime
        })
    },
    //日期转化为星期
    getWeekday(date){
      var date = new Date(date);
        var weekday=new Array(7);
        weekday[0]="星期日"
        weekday[1]="星期一"
        weekday[2]="星期二"
        weekday[3]="星期三"
        weekday[4]="星期四"
        weekday[5]="星期五"
        weekday[6]="星期六"
      var week = weekday[date.getDay()];
        return week
    },
    //数组重拼接
    resetList(list){
        let newList = [];
        for(var i=0;i<list.length;i++){
            for(var j=i+1;j<list.length;j++){
                if(list[i].date === list[j].date){
                    let temporary = [];
                    temporary.push(list[i]);
                    temporary.push(list[j]);
                    newList.push(temporary)
                }
            }
        }
        for(var a = 0;a<newList.length;a++){
           if(newList[a][0].status != 1){
               let abc = newList[a][0];
               newList[a][0] = newList[a][1];
               newList[a][1] = abc;
           }
        }
        return newList
    },
    shoppingcartAdd(e){
        let id= e.currentTarget.dataset.id;
        let _this = this;
        let shoppingcartList = _this.data.shoppingcartList;
        let num,price,productId;
        for(var i in shoppingcartList){
            if(shoppingcartList[i].id == id){
                productId = shoppingcartList[i].product_id;
                num = ++shoppingcartList[i].num;
                price = shoppingcartList[i].price;
            }
        }
        util.getAjax(`${app.globalData.apiUrl}/operation_community_service_kitchen_product_buycar`,res=>{
            _this.getShoppingcartList();
        },{
            type:2,
            kitchen_id:_this.data.kitchenId,
            product_id:productId,
            user_id:app.globalData.userId,
            num:num,
            price:price,
            id:id
        })
   },
    reduceShoppingcart(e){
      let id = e.currentTarget.dataset.id;
      let _this = this;
      let shoppingcartList = _this.data.shoppingcartList;
      let num,price,productId;
      for(var i in shoppingcartList){
          if(shoppingcartList[i].id == id){
              productId = shoppingcartList[i].product_id;
              num = --shoppingcartList[i].num;
              price = shoppingcartList[i].price;
          }
      }
      util.getAjax(`${app.globalData.apiUrl}/operation_community_service_kitchen_product_buycar`,res=>{
          _this.getShoppingcartList();
      },{
          type:2,
          kitchen_id:_this.data.kitchenId,
          product_id:productId,
          user_id:app.globalData.userId,
          num:num,
          price:price,
          id:id
      })
    },
    //立即购买
    buyNow(e){
        if(app.globalData.userId){
            let id = e.currentTarget.dataset.id;
            wx.navigateTo({
                url:'/subPages/pensionService/confirmOrder/confirmOrder?type=1&id='+id
            })
        }else{
            util.showModelAll('提示','该功能需要授权登录后使用，请进行授权登录',function(){
                if (app.globalData.userInfo) {
                    //已授权
                    wx.redirectTo({
                        url: '/pages/login/login'
                    })
                }else{
                    // 在没有 open-type=getUserInfo 版本的兼容处理
                    if(app.globalData.isAuthorized){
                        app.userInfoReadyCallback = res => {
                          if (res) {
                            //已授权
                            wx.redirectTo({
                              url: '/pages/login/login'
                            })
                          }else{
                            //未授权
                            wx.navigateTo({
                              url: '/pages/authorizedLogin/authorizedLogin?isLogin='+ false,
                            })
                          }
                        }
                    }else{
                        wx.navigateTo({
                          url: '/pages/authorizedLogin/authorizedLogin?isLogin='+ false,
                        })
                    }
                }
            })
        }
    },
    //购物车结算
    toOrder(){
      let that = this;
        if(that.data.shoppingcartNum!=0){
            wx.navigateTo({
                url:'/subPages/pensionService/confirmOrder/confirmOrder?type=2'
            })
        }else{
            util.showToast('请先加购物车在购买','none',2000);
        }

    },
    clearShoppingcart(){
        let _this = this;
        util.getAjax(`${app.globalData.apiUrl}/operation_community_service_kitchen_product_buycar`,res=>{
            _this.getShoppingcartList()
        },{
            type:3,
            kitchen_id:_this.data.kitchenId,
            user_id:app.globalData.userId
        })
    },
    //获取购物车
    getShoppingcartList(){
      let _this = this;
      util.getAjax(`${app.globalData.apiUrl}/get_community_service_kitchen_buycar`,res=>{
          //计算总数
          let money = 0;
          for(var i in res.data){
              money += res.data[i].num * res.data[i].price
          }
          _this.setData({
              shoppingcartList:res.data,
              shoppingcartNum:res.data.length,
              totalMoney:money.toFixed(2)
          })
      },{
          user_id:app.globalData.userId,
          kitchen_id:_this.data.kitchenId
      })
    },
    //购物车操作 type 1 加入购物车  2 减少购物车数量  3 清空购物车
    
    //获取服务数据异常
    shopDataErr(err){
      let _this = this;
        if(p>1){
            loadMoreView.loadMoreFail()
        }else{
            util.showModal('提示','获取商品失败，请向上滑动屏幕')
            _this.setData({
                isFail: true
            })
        }
    },
    loadMoreListener: function(e) {
      let _this = this;
        p += 1
        this.getKitchenContent(_this.data.currentNav,_this.data.kitchenId)
    },

    clickLoadMore: function(e) {
      let _this = this;
        this.getKitchenContent(_this.data.currentNav,_this.data.kitchenId)
    },
    //预定订单
    reserve(e){
        if(app.globalData.userId){
            //type 1 单  2 所有
            var type = e.currentTarget.dataset.type;
            var _this = this;
            var productId = [];
            var index = '';
                console.log(type);
                if(type == 1){
                    index = e.currentTarget.dataset.index;
                    console.log(index);
                    var productList = _this.data.productList[index];
                    console.log(productList);
                    for(var i in productList){
                        productId.push(productList[i].id)
                    }
                    console.log(productId);
                }
                if(type == 2){
                    var productList = this.data.productList;
                    for(var i in productList){
                        for(var j in productList[i]){
                            console.log(productList[i][j].id);
                            productId.push(productList[i][j].id)
                        }
                    }
                }
                console.log(productId);
                wx.navigateTo({
                    url:'/subPages/pensionService/reserveComfirm/reserveComfirm?type='+type+'&productid='+productId
                })
        }else{
            util.showModelAll('提示','该功能需要授权登录后使用，请进行授权登录',function(){
                if (app.globalData.userInfo) {
                    //已授权
                    wx.redirectTo({
                        url: '/pages/login/login'
                    })
                }else{
                    // 在没有 open-type=getUserInfo 版本的兼容处理
                    if(app.globalData.isAuthorized){
                        app.userInfoReadyCallback = res => {
                          if (res) {
                            //已授权
                            wx.redirectTo({
                              url: '/pages/login/login'
                            })
                          }else{
                            //未授权
                            wx.navigateTo({
                              url: '/pages/authorizedLogin/authorizedLogin?isLogin='+ false,
                            })
                          }
                        }
                    }else{
                        wx.navigateTo({
                          url: '/pages/authorizedLogin/authorizedLogin?isLogin='+ false,
                        })
                    }
                }
            })
        }
      
    },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
      this.getKitchen();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
      let _this = this;
      if(this.data.isFail){
          this.getKitchenContent(_this.data.currentNav,_this.data.kitchenId)
          return
      }
      loadMoreView.loadMore()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
    //获取changetype  height
    getChangeH(){
        let _this = this;
        const query = wx.createSelectorQuery()
        query.select('.change-type').boundingClientRect(
            function (res) {
                console.log(res.height);
                _this.setData({
                    changeH:res.height
                })
            }
        ).exec();
    },

  /*
  * 用户滚动条
  */
  onPageScroll:function(res){
      var that = this;
      if(res.scrollTop >= this.data.changeH){
          that.setData({
              isFixed:true
          })
      }else{
          that.setData({
              isFixed:false
          })
      }
  }
})
